﻿/**************************************************************
 *
 * 命名空间：Sgr.DataCategories.Application.Commands.AdministrativeDivisions
 * 创建时间：2025/3/19
 * 描述：创建行政区划命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.DataCategories.Domain.AdministrativeDivisions;
using Sgr.Domain.Uow;
using Sgr.Modules;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.DataCategories.Application.Commands.AdministrativeDivisions
{
    /// <summary>
    /// 创建行政区划命令处理器
    /// </summary>
    public class CreateAdministrativeDivisionCommandHandler
        : IRequestHandler<CreateAdministrativeDivisionCommand, CommandResult<bool>>
    {
        private readonly IAdministrativeDivisionManage _administrativeDivisionManage;
        private readonly IAdministrativeDivisionRepository _administrativeDivisionRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="administrativeDivisionManage">行政区划管理器</param>
        /// <param name="administrativeDivisionRepository">行政区划仓储</param>
        public CreateAdministrativeDivisionCommandHandler(
            IAdministrativeDivisionManage administrativeDivisionManage,
            IAdministrativeDivisionRepository administrativeDivisionRepository)
        {
            _administrativeDivisionManage = administrativeDivisionManage;
            _administrativeDivisionRepository = administrativeDivisionRepository;
        }

        /// <summary>
        /// 处理创建行政区划命令
        /// </summary>
        /// <param name="request">命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(
            CreateAdministrativeDivisionCommand request,
            CancellationToken cancellationToken)
        {
            // 创建行政区划实体
            string pinyinName = PinYinConverterHelper.ToPinyin(request.Name);
            string pinyinAbbr = PinYinConverterHelper.ToFirstPinyin(request.Name);
            var entity = await _administrativeDivisionManage.CreateNewAsync(
                request.Name,
                request.Code,
                request.OrderNumber,
                Sgr.Domain.Entities.EntityStates.Normal,
                request.ShortName,
                pinyinName,
                pinyinAbbr,
                request.Description,
                request.ParentId,
                cancellationToken);

            // 保存实体
            await _administrativeDivisionRepository.InsertAsync(entity, cancellationToken);

            return CommandResult.Success(true);
        }
    }
}